package com.ess.project.examine.record.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.ess.project.examine.record.domain.ExamineRecordEntity;
import com.ess.project.examine.record.mapper.RecordMapper;
import com.ess.project.examine.record.service.IRecordService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Date: Created in 2:51 下午 2021/3/6
 * @Author: daihui
 * @Modified By:
 */
@Slf4j
@Component
public class ExamineRecordEntityListener extends AnalysisEventListener<ExamineRecordEntity> {


    private static final int BATCH_COUNT = 10;
    public static final String PERSONNEL_TYPE = "人员类别：";

    List<ExamineRecordEntity> list = new ArrayList<>();


    private final IRecordService recordService;

    public ExamineRecordEntityListener(IRecordService recordService) {
        this.recordService = recordService;
    }

    private static String personnelCategory = "";
    private static String examineTime = "";

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        if(PERSONNEL_TYPE.equals(headMap.get(10))){
            personnelCategory = headMap.get(11);
            examineTime = headMap.get(13);
        }
        log.info("人员类别:{},考核时间:{}", personnelCategory,examineTime);
    }


    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     * @param context
     */
    @Override
    public void invoke(ExamineRecordEntity data, AnalysisContext context) {
        data.setPersonnelCategory(personnelCategory);
        data.setExamTime(examineTime);
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            this.saveData();
            list.clear();
        }
    }


    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        this.saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        recordService.saveBatch(list);
    }

}
